<?php

namespace app\controller;

use app\model\User;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Request;
use think\response\Json;
use captcha\Captcha;

class Account
{
    /**
     * 用户注册
     * @param Request $request
     * @return Json
     */
    public function register(Request $request): Json
    {
        $username = $request->post('username');
        $password = $request->post('password');

        // 检查用户名是否已存在
        $exist = (new User)->where('username', $username)->count();
        if ($exist > 0) {
            return apiResponse(403, '用户名已存在，注册失败');
        }

        // 生成密码的哈希值
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        // 插入新用户记录
        $user = new User();
        $user->username = $username;
        $user->password = $passwordHash;
        $user->save();

        return apiResponse(200, '注册成功，正在为您跳转页面...');
    }

    /**
     * 用户登录
     * @param Request $request
     * @return Json
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function login(Request $request): Json
    {
        $payload = $request->post();
        try {
            validate(\app\validate\User::class)->check($payload);
            //判断验证码是否正确
            $captcha = new Captcha();
            $exist = $captcha->check($payload['captcha'], $payload['hash']);
            if (!$exist) {
                return apiResponse(500, '验证码不正确，请检查重试！');
            }
            // 根据手机号码查询用户信息
            $user = (new User)->where('mobile', $payload['mobile'])->find();
            if (!$user) {
                return apiResponse(403, '用户不存在，登录失败');
            }

            // 验证密码
            if (!password_verify($payload['password'], $user->password)) {
                return apiResponse(403, '密码不正确，登录失败');
            }
            // 生成JWT Token
            $payload = [
                'user_id' => $user->id,
                'username' => $user->username,
                'slt' => $payload['captcha'],
                'exp' => time() + 3600 // 过期时间为1小时
            ];
            $enterprises = (new \app\model\Enterprise())->getEnterpriseListByUserId($user->id);
            //组合返回数据
            $data = [
                'userinfo'=>[
                    'id' => $user->id,
                    'username' => $user->username,
                    'avatar' => $user->avatar
                ],
                // token
                'token' => generateToken($payload),
                // 用户企业列表
                'enterprise'=> $enterprises,
            ];
            return apiResponse(200, '登录成功，正在为你跳转页面...', $data);
        } catch (ValidateException $e) {
            return apiResponse(403, $e->getMessage());
        }
    }

    public function captcha($w = 125, $h = 40, $v = ""): Json
    {
        try {
            $config = ['imageW' => $w, 'imageH' => $h, 'fontSize' => 22];
            $captcha = new Captcha($config);
            $res = $captcha->create();
            return apiResponse(200, '验证码生成成功', $res);
        }catch (\Exception $e){
            return apiResponse(403, $e->getMessage());
        }
    }
}
